#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: Florian Dorn <florian.dorn@gmail.com>
# @package: agenda
# @license: GNU GPLv2
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

import sys
import os
from stat import *
import gobject

import datetime
_instances = {}
_plugins = []

""" holds the instances to all loaded plugins"""


class Plugin(gobject.GObject):
	capabilities = []
	config_defaults = [] #a map of value: default-pairs.
	options = {}
	Plugin_Name = ""
	Plugin_Author = ""	
	Plugin_Website = ""
	active = False
	def set_active(self,active):
		self.active  =active
	def __init__(self):
		gobject.GObject.__init__(self)
		self.options = {}
	def setOption(self,name,value):
		self.options[name] = value
	def getOption(self,name):
		return self.options.get(name)
	def __repr__(self):
		return '<%s %r>' % (
			self.__class__.__name__,
			self.capabilities
		)
	def setOptions(self,vals):
		for key in vals:
			self.options[key] = vals[key]
	def __str__(self):
		return self.__module__
def load_plugins(plugins):
	print "Loading plugins: %s" % ", ".join(plugins)
	
	for plugin in plugins:
		start = datetime.datetime.now()
		try:
			__import__(plugin, globals(), locals(),  ['plugins'])
		except Exception, e:
			print "Could not load %s Plugin" % plugin
			print e
		print "%s: %s" % (plugin, datetime.datetime.now() - start)
	pass

def init_plugin_system():
	
	plugin_p = os.path.realpath(os.path.join(os.path.dirname( __file__ ),'plugins'))

	#print "Initializing plugin system..."
	plugins = []
	if not plugin_p in sys.path:
		sys.path.insert(0, plugin_p)
	try:
		names = os.listdir(plugin_p)
		for name in names:
			try:
				st = os.lstat(os.path.join(plugin_p, name,'__init__.py'))
				if(S_ISREG(st.st_mode)):
					plugins.append(name)
			except os.error:
				continue
		load_plugins(plugins)
	except Exception,e:
		print "Could not read plugin folder %s" % plugin_p
		print e


def get_all_plugins(base = None):
	"""return all subclasses of CalendarProviderBase"""
	result = []
	if(base == None):
		base = Plugin.__subclasses__()
	#print base
	for plugin in base:
		##somehow every plugin is also in this list with module..classname
		if(("%s" % plugin).find('..')) != -1:
			continue
		result.append(plugin)
		if(plugin.__subclasses__()):
			result.extend(get_all_plugins(plugin.__subclasses__()))
			
	
	return result

def get_by_capability(capability):
	result = []
	for plugin in get_all_plugins():
		if capability in plugin.capabilities:
			#print plugin
			if plugin in _instances:
				result.append(_instances[plugin])
	return result
	
def load_by_capability(capability,shell):
	result = []
	for plugin in get_all_plugins():
		if capability in plugin.capabilities:
			#print plugin
			if not plugin in _instances:
				print plugin
				_instances[plugin] = plugin(shell)
				#_instances[plugin].loadConfig()
				#TODO: automatically load the preferences of this plugin
			result.append(_instances[plugin])
	return result


